<template>
  <el-card class="app-container">
    <div v-if="!open">
      <div class="itemTitle">人员管理</div>
      <div class="search">
        <el-form
          :inline="true"
          :model="queryParams"
          ref="queryForm"
          class="demo-form-inline"
          label-width="120"
        >
          <el-row>
            <el-col :span="5">
              <el-form-item label="姓名" prop="name">
                <el-input
                  @keyup.enter.native="handleQuery"
                  v-model="queryParams.name"
                  placeholder="请输入姓名"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="企业" prop="contractorId">
                <el-select
                  v-model="queryParams.contractorId"
                  placeholder="请选择企业"
                  clearable
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.id"
                    :label="dict.companyName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否黑名单" prop="contractorId">
                <el-select
                  v-model="queryParams.contractorId"
                  placeholder="请选择企业"
                  clearable
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.id"
                    :label="dict.companyName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="人员类型" prop="contractorId">
                <el-select
                  v-model="queryParams.contractorId"
                  placeholder="请选择企业"
                  clearable
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.id"
                    :label="dict.companyName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item>
                <el-button type="primary" @click="handleQuery">搜索</el-button>
                <el-button @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="content">
        <!-- <div class="ct-btns">
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="success" @click="handleImport">批量导入</el-button>
          <el-button type="warning" @click="handleExport">批量导出</el-button>
          <el-button type="info" @click="importTemplate"
            >下载导入模版</el-button
          >
        </div> -->
        <div class="ct-table">
          <elTables
            :table-data="tableData"
            :columns="tableColumns"
            :handle-current-change="handleCurrentChange"
            isPagin
            :curHeight="tableHeight"
          />
        </div>
      </div>
    </div>
    <div v-else class="page-edit">
      <header>
        <i
          style="font-size: 18px; cursor: pointer; margin-right: 8px"
          class="el-icon-arrow-left"
          @click="open = !open"
        ></i>
        <span>{{ title }}</span>
      </header>
      <section class="edit-body">
        <!-- <el-steps :active="active" finish-status="success">
          <el-step title="第一步" description="填写个人信息"></el-step>
          <el-step title="第二步" description="外来人员安全须知确认"></el-step>
          <el-step
            title="第三步"
            description="安全生产管理协议书确认"
          ></el-step>
          <el-step title="第四步" description="上传技术交底单"></el-step>
        </el-steps> -->
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          :readonly="readonly"
          label-width="220px"
        >
          <el-row>
            <el-col
              :span="item.span"
              v-for="(item, index) in formList"
              :key="index"
            >
              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  style="width: 100%"
                  v-model.trim="form[item.prop]"
                  :maxlength="item.maxlength"
                  :readonly="readonly"
                  :disabled="readonly"
                  :placeholder="'请输入' + item.label"
                />
              </el-form-item>
              <!-- inputNumber -->
              <el-form-item
                v-if="item.type == 'inputNumber'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  style="width: 100%"
                  v-model.number="form[item.prop]"
                  :maxlength="item.maxlength"
                  :readonly="readonly"
                  :disabled="readonly"
                  :placeholder="'请输入' + item.label"
                />
              </el-form-item>

              <!-- inputPhone -->
              <el-form-item
                v-if="item.type == 'inputPhone'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  style="width: 100%"
                  v-model.trim="form[item.prop]"
                  :maxlength="item.maxlength"
                  :readonly="readonly"
                  :disabled="readonly"
                  :placeholder="'请输入' + item.label"
                />
              </el-form-item>
              <el-form-item
                v-if="item.type == 'textarea'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-input
                  show-word-limit
                  type="textarea"
                  :rows="3"
                  style="width: 100%"
                  v-model.trim="form[item.prop]"
                  :maxlength="item.maxlength"
                  :readonly="readonly"
                  :disabled="readonly"
                  :placeholder="'请输入' + item.label"
                />
              </el-form-item>
              <!-- select -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-select
                  v-model="form[item.prop]"
                  :placeholder="'请选择' + item.label"
                  clearable
                  :readonly="readonly"
                  :disabled="readonly"
                >
                  <el-option
                    v-for="dict in statusOptions"
                    :key="dict.id"
                    :label="dict.companyName"
                    :value="dict.id"
                  />
                </el-select>
              </el-form-item>
              <!-- switch -->
              <el-form-item
                v-if="item.type == 'switch'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-switch
                  v-model="form[item.prop]"
                  :active-value="1"
                  :inactive-value="0"
                >
                </el-switch>
              </el-form-item>
              <!-- date -->
              <el-form-item
                v-if="item.type == 'date'"
                :label="item.label"
                :prop="item.prop"
              >
                <el-date-picker
                  :readonly="readonly"
                  :disabled="readonly"
                  style="width: 100%"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  v-model="form[item.prop]"
                  type="date"
                  :placeholder="'请选择' + item.label"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </section>
      <footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="cancel" style="margin-right: 10px"
            >取 消</el-button
          >
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </footer>
    </div>

    <el-dialog title="电子签名" :visible.sync="signinVisible" width="700px">
      <!-- <signinDia @setsignin="setsignin"></signinDia> -->
    </el-dialog>
    <!-- 导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="800px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>

</template>
  <script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
// import signinDia from "@/components/signinDia.vue";
import {
  pageContractorPersonnel,
  getContractorPersonnel,
  delContractorPersonnel,
  addContractorPersonnel,
  updateContractorPersonnel,
  exportContractorPersonnel,
  downImportTemplate,
} from "@/api/thridParty/index.js";
import { listContractor } from "@/api/specialWork/contractor";
import { getToken } from "@/utils/auth";
export default {
  data() {
    const checkMobile = (rule, value, cb) => {
      if (value) {
        const regMobile = /^1[3,4,5,6,7,8,9][0-9]{9}$/;
        if (regMobile.test(value)) {
          return cb();
        } else if (!rule.required && !value) {
          return cb();
        } else {
          cb(new Error("请输入正确的手机号"));
        }
      } else {
        return cb();
      }
    };
    const checkIdentityId = (rule, value, cb) => {
      const regMobile = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      if (regMobile.test(value)) {
        return cb();
      } else if (!rule.required && !value) {
        return cb();
      } else {
        cb(new Error("请输入正确的身份证号"));
      }
    };
    return {
      userId: "",
      aptitude: false,
      tableHeight: 0,
      active: 0, //步骤条进度
      tableColumns: [
        { key: "name", title: "姓名" },
        { key: "contractorName", title: "企业" },
        { key: "age", title: "年龄" },
        { key: "identityId", title: "身份证号" },
        { key: "phone", title: "负责人联系方式" },
        {
          title: "是否黑名单",
          key: "blackStatus",
          render: (h, params) => {
            return h("div", [
              h("el-switch", {
                props: {
                  value: params.row.blackStatus == 0 ? false : true,
                },
                on: {
                  change: () => {
                    this.handleStatusChange(params.row);
                  },
                },
              }),
            ]);
          },
        },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          render: (h, params) => {
            return h("div", [
              // h(
              //   "el-button",
              //   {
              //     props: {
              //       type: "text",
              //       size: "small",
              //     },
              //     on: {
              //       click: () => {
              //         this.jumpAptitude(params.row);
              //       },
              //     },
              //   },
              //   "资质"
              // ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.handleLook(params.row);
                    },
                  },
                },
                "查看"
              ),
              // h(
              //   "el-button",
              //   {
              //     props: {
              //       type: "text",
              //       size: "small",
              //     },
              //     on: {
              //       click: () => {
              //         this.handleUpdate(params.row);
              //       },
              //     },
              //   },
              //   "编辑"
              // ),
              // h(
              //   "el-button",
              //   {
              //     props: {
              //       type: "text",
              //       size: "small",
              //     },
              //     on: {
              //       click: () => {
              //         this.handleDelete(params.row);
              //       },
              //     },
              //   },
              //   "删除"
              // ),
            ]);
          },
        },
      ],
      rules: {
        name: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: ["blur", "change"],
          },
        ],
        contractorId: [
          {
            required: true,
            message: "企业名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        age: [
          {
            required: true,
            message: "年龄不能为空",
            trigger: ["blur", "change"],
          },
        ],
        identityId: [
          {
            required: true,
            message: "身份证号码不能为空",
            trigger: ["blur", "change"],
          },
          {
            validator: checkIdentityId,
            trigger: "blur",
          },
        ],
        phone: [
          {
            required: true,
            message: "负责人联系方式不能为空",
            trigger: ["blur", "change"],
          },
          {
            validator: checkMobile,
            trigger: "blur",
          },
          { min: 11, max: 11, message: "长度在 11个字符", trigger: "blur" },
        ],
        blackStatus: [
          {
            required: true,
            message: "请选择是否加入黑名单",
            trigger: ["blur", "change"],
          },
        ],
      },
      title: "",
      tableData: [],
      queryParams: {
        ...defaultQueryParams,
        name: "",
        contractorId: "",
      },
      formList: [
        {
          label: "姓名",
          prop: "name",
          span: 8,
          type: "input",
          maxlength: 30,
        },

        {
          label: "企业",
          prop: "contractorId",
          span: 8,
          type: "select",
          maxlength: 50,
        },
        {
          label: "身份证号码",
          prop: "identityId",
          span: 8,
          type: "input",
          maxlength: 18,
        },
        {
          label: "年龄",
          prop: "age",
          span: 8,
          type: "inputNumber",
          maxlength: 50,
        },
        {
          label: "负责人联系方式",
          prop: "phone",
          span: 8,
          type: "inputPhone",
          maxlength: 11,
        },
        {
          label: "是否黑名单",
          prop: "blackStatus",
          span: 8,
          type: "switch",
        },
      ],
      form: {},
      open: false,
      total: 22,
      signinVisible: false, //签名组件弹窗
      // 状态数据字典
      statusOptions: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/specialWork/ContractorPersonnel/importData",
      },
    };
  },
  components: {
    // signinDia,
  },
  async created() {
    let res = await listContractor();
    this.statusOptions = res.data;
    if (this.$route.query.id) {
      this.queryParams.contractorId = this.$route.query.id * 1;
      this.handleQuery();
    } else {
      this.getPage();
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    });
  },
  methods: {
    //资质按钮跳转
    jumpAptitude(row) {
      this.aptitude = true;
      this.userId = row.id;
    },
    getAptitude(val) {
      this.aptitude = val;
    },
    //签名图片
    setsignin(img) {
      console.log(img);
      this.signinVisible = false;
    },
    /** 查询承包商管理列表 */
    getPage() {
      this.loading = true;
      pageContractorPersonnel(this.queryParams).then((response) => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //是否黑名单
    handleStatusChange(row) {
      let text = row.blackStatus == 0 ? "加入黑名单" : "退出黑名单";
      let obj = JSON.parse(JSON.stringify(row));
      let that = this;
      this.$modal
        .confirm("确认要" + text + "吗？")
        .then(function () {
          obj.blackStatus = row.blackStatus == "1" ? "0" : "1";
          return updateContractorPersonnel({
            ...obj,
          });
        })
        .then(() => {
          that.$modal.msgSuccess("操作成功");
          that.getPage();
        })
        .catch(function () {
          that.getPage();
        });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractorId: null,
        name: null,
        age: null,
        identityId: null,
        phone: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {};
      this.open = true;
      this.reset();
      this.title = "新增第三方人员";
      this.readonly = false;
    },
    /** 查看 */
    handleLook(row) {
      this.reset();
      const id = row.id;
      getContractorPersonnel(id).then((response) => {
        this.form = response.data;
        this.form.blackStatus = this.form.blackStatus * 1;
        this.open = true;
        this.readonly = true;
        this.title = "查看第三方人员";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getContractorPersonnel(id).then((response) => {
        this.form = response.data;
        this.form.blackStatus = this.form.blackStatus * 1;
        this.readonly = false;
        this.open = true;
        this.title = "修改第三方人员";
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出第三方人员管理数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportContractorPersonnel(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    /** 下载模板操作 */
    importTemplate() {
      downImportTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "第三方人员导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getPage();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delContractorPersonnel([ids]);
        })
        .then(() => {
          this.getPage();
          this.msgSuccess("删除成功");
        });
    },
    getTableHeight() {
      let height = document.getElementsByClassName("ct-table")[0].clientHeight;
      console.log("height", height);
      this.tableHeight = height - 40;
    },
    /** 提交按钮 */
    submitForm() {
      // if (this.active++ > 3) this.active = 0;
      // return;
      this.form.factoryId = 2;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateContractorPersonnel(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addContractorPersonnel(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    // 提交导入文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>    
<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__body {
  padding: 30px 20px !important;
  text-align: center;
}
</style>